import csv
import random
import json
import logging


# Read maps of interest group ids and vote ids to other info
rating_map = {}
vote_info_map = {}
with open('vote_and_group_info_map.csv', 'rbU') as csvfile:
	r = csv.DictReader(csvfile, delimiter=',')
	for row in r:
		rating_map['rating' + row['sig_id']] = row
		vote_info_map['vote' + row['house_vote_id']] = row

#print 'rating_map: %s' % json.dumps(rating_map, sort_keys = True, indent = 4)
#print '\nvote_info_map: %s' % vote_info_map

# Read in CSV to dictionary in memory, indexed by candidate ID.
cands = {}
with open('processed_MCs_for_api.csv', 'rbU') as csvfile:
	r = csv.DictReader(csvfile, delimiter=',')
	for row in r:
		cands[row['candidateid']] = row

# Maps votes to human interpretation
vote_map = {'0': 'No', '1': 'Yes'}

def _constructAPIResponse(candidate_id, survey_version):
	assert survey_version in ['a', 'b'], 'Invalid survey version: %s' % survey_version

	full_dict = cands[candidate_id]
	#print json.dumps(full_dict, sort_keys=True, indent = 4, separators=(',', ': '))

	# Candidate info to return in response
	response = {}
	for key in ['candidateid', 'longname', 'shortname', 'partyoneletter']:
		response[key] = full_dict[key]

	# Determine ratings and votes that are eligible to show
	eligible_ratings = []
	eligible_votes = []
	for key, value in full_dict.iteritems():
		if value == '': # Skip empty ratings and votes
			pass
			#print 'Skipped over key %s with value %s' % (key, value)
		else:
			if key.startswith('rating'):
				corresponding_vote = rating_map[key]['house_vote_id']
				if rating_map[key]['split'] == survey_version:
					if full_dict['vote' + corresponding_vote] != '': # make sure there is a corresponding vote
						eligible_ratings.append(key)
			elif key.startswith('vote'):
				if vote_info_map[key]['split'] == survey_version:
					eligible_votes.append(key)

	# Heuristics project:
	# Randomly choose a rating to show from the list of eligible ratings and read in info about it and the corresponding vote
	if int(candidate_id) in [47930, 69553, 123390, 125031, 138524, 168594]:
		response['heuristics_eligible'] = 'FALSE'
	else:
		assert len(eligible_ratings) >= 1, 'No eligible ratings'
		response['heuristics_eligible'] = 'TRUE'
		randomly_selected_sig_id = random.sample(eligible_ratings, 1)[0]
		response['num_eligible_ratings'] = len(eligible_ratings)
		response['randomrating_sig_rating'] = full_dict[randomly_selected_sig_id]
		for k in ['sig_name', 'sig_id', 'vote_bill_title', 'house_vote_id', 'vote_description_for_respondent']:
			response['randomrating_' + k] = rating_map[randomly_selected_sig_id][k]

	# Issue publics project:
	# Randomly choose three issues to show from the list of eligible votes and read in info about them
	if int(candidate_id) in [26344, 123390]:
		response['issuepub_eligible'] = 'FALSE'
	else:
		assert len(eligible_votes) >= 3, 'Only %s eligible votes' % len(eligible_votes)
		response['issuepub_eligible'] = 'TRUE'
		response['num_eligible_votes'] = len(eligible_votes)
		randomvotes = random.sample(eligible_votes, 3)
		for i in [1,2,3]:
			response['randomvote' + '_id_' + str(i)] = randomvotes[i-1]
			response['randomvote' + '_result_'  + str(i)] = vote_map[full_dict[randomvotes[i-1]]]
			for k, v in vote_info_map[randomvotes[i-1]].iteritems():
				if k in ['id', 'result', 'vote_bill_title', 'vote_description_for_respondent']:
					response['randomvote_' + k + '_' + str(i)] = v

	return response



def tryBothSurveyAPIResponse(candidate_id):
	survey_version = random.sample(['a','b'], 1)[0]
	try:
		logging.info('Trying with survey version %s.', survey_version)
		result = _constructAPIResponse(candidate_id, survey_version)
	except Exception as e:
		logging.info('Failed because %s. Trying other version.', str(e))
		try:
			if survey_version == 'a':
				survey_version = 'b'
			else:
				survey_version = 'a'
			result = _constructAPIResponse(candidate_id, survey_version)
		except Exception as e:
			logging.error('Failed because %s on candidate %s. Both versions tried.', str(e), candidate_id)
			return {'success': 'FALSE'}
	
	logging.info('API response constructed. Politician is %s.', result['shortname'])
	result['survey_version'] = survey_version
	result['success'] = 'TRUE'
	return result



if __name__ == '__main__':
	print _constructAPIResponse('47930', 'a')

	#print _constructAPIResponse('81569', 'a')

	# Print Nancy Pelosi as an example.
	print json.dumps(_constructAPIResponse('26732', 'a'), indent = 4, sort_keys = True)
	print json.dumps(_constructAPIResponse('26732', 'b'), indent = 4, sort_keys = True)

	# Try Paul Ryan as an example
	print json.dumps(_constructAPIResponse('26344', 'a'), indent = 4, sort_keys = True)
	print json.dumps(_constructAPIResponse('26344', 'b'), indent = 4, sort_keys = True)


	# TO DO: try all the candidates

	#for k in sorted(constructAPIResponse('26732').keys()):
	#	print '${e://Field/%s}' % k


